<!--奖品列表-->
<template>
  <el-card shadow="never">
    <div class="flex-between m-bottom20">
      <div class="fit-title">奖品列表</div>
      <el-button type="text" icon="el-icon-circle-plus" @click="addRow()"
      :disabled="tableData.length >= 6 && activityType==2 || tableData.length >= 8 && activityType==3 ? true : false">
        添加奖品</el-button>
    </div>
<!--    报错与:model="tableData"有关-->
    <el-form
      :model="tableData"
      ref="tableData"
      :inline="true"
      label-width="100px"
      :rules="handleFormRules"
    >
      <el-table
        class="table-item"
        max-height="273px"
        :data="tableData"
        ref="table"
        tooltip-effect="dark"
        border
        stripe>
        <el-table-column  label="奖品名称" align="center">
          <template slot-scope="scope">
            <el-form-item
              :prop="scope.$index + '.prizeName'"
              :rules="handleFormRules.prizeName"
              size="mini"
            >
              <el-input v-model="scope.row.prizeName"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <!--<el-table-column label="奖品图片" align="center">
          <template slot-scope="scope">
            <el-form-item
              :prop="scope.$index + '.prizePicture'"
              :rules="handleFormRules.prizePicture"
              size="mini"
            >
              <el-upload
                :on-change="onUpload"
                class="avatar-uploader flex"
                :action="ossUrl"
                :show-file-list="false"
                :on-success="(response, file, fileList) => {handleAvatarSuccess(response, file, fileList,scope)}"
                :before-upload="beforeAvatarUpload">
                &lt;!&ndash;imgUrl 替换 scope.row.prizePicture&ndash;&gt;
                <img v-if="scope.row.prizePicture.length" :src="scope.row.prizePicture" class="avatar">
                <div v-else class="avatar-uploader-icon flex-column">
                  <i class="el-icon-picture"></i>
                  <div>上传背景</div>
                </div>
              </el-upload>
            </el-form-item>
          </template>
        </el-table-column>-->
        <el-table-column label="数量" align="center">
          <template slot-scope="scope">
            <el-form-item
              :prop="scope.$index + '.quantity'"
              :rules="handleFormRules.quantity"
              size="mini"
            >
              <el-input class="delInput" type="number" v-model.number="scope.row.quantity"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="中奖率%" align="center">
          <template slot-scope="scope">
            <el-form-item
              :prop="scope.$index + '.winningPercentage'"
              :rules="handleFormRules.winningPercentage"
              size="mini"
            >
              <el-input class="delInput" type="number" v-model.number="scope.row.winningPercentage"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="用户可中次数" align="center">
          <template slot-scope="scope">
            <el-form-item
              :prop="scope.$index + '.medianFrequency'"
              :rules="handleFormRules.medianFrequency"
              size="mini"
            >
              <el-input class="delInput" type="number" v-model.number="scope.row.medianFrequency"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <div class="red pointer" @click="deleteRow(scope.$index, tableData)">删除</div>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <el-button type="primary" class="tj-class" @click="confirm">确定提交</el-button>
  </el-card>
</template>

<script>
  import {userOssSignature} from "@/api/creatCenter/material";
  import {getToken} from "@/utils/token-util";
  import axios from "axios";
  export default {
    name: "prize",
    props:{
      // 需测试
      forms:Array | Object
      // activityType:Number,
    },
    data() {
      return {
        activityType:this.forms.activityType,
        //定义的表格数据
        handleFormRules: {
          prizeName: [
            {
              required: true,
              message: '请输入奖品名称',
              trigger: 'change',
            },
          ],
          /*prizePicture: [
            {
              required: true,
              message: '请上传奖品图片',
              trigger: 'change',
            },
          ],*/
          quantity: [
            {
              required: true,
              message: '请输入数量',
              trigger: 'change',
            },
          ],
          winningPercentage: [
            {
              required: true,
              message: '请输入中奖率',
              trigger: 'change',
            },
          ],
          medianFrequency: [
            {
              required: true,
              message: '请输入用户可中次数',
              trigger: 'change',
            },
          ]
        },
        // 上传背景图片url
        fileList:[],
        // 背景图
        imageUrl: '',
        list:[],
        table:{},
        // 奖品列表数据
        tableData: this.forms.listofprizes&&this.forms.listofprizes.length>0 ? this.forms.listofprizes : []
      }
    },
    created(){
      console.log("111111111111this.forms==========",this.forms)
    },
    methods:{
      init(item){
        console.log("initaaaaaaaaaaaaaaaaaaaaaaaaaaaa",item)
        this.forms=item
        this.activityType=this.forms.activityType
        console.log("initaaaaaaaaaaaaaaaaaaaaaaaaaaaa222",this.activityType)

      },
      refresh(){
        this.$nextTick(() => {
          // 且勿滥用
          this.$refs.tableData.resetFields()
        })
      },
      uploadByWxhgz(file, fileList) {
        if (fileList.length > 1) {
          fileList.splice(0, 1);
        }
        console.log("fileList",fileList)
        // 执行其他操作
      },
      /* 上传 */
      onUpload(file) {
        this.fileList.push(file)
        console.log('this.fileList',this.fileList)
      },
      handleAvatarSuccess(response, file, fileList,scope){
        console.log('file',file,'response',response,URL.createObjectURL(file.raw))
        this.tableData[scope.$index].prizePicture= URL.createObjectURL(file.raw)
        this.tableData[scope.$index].raw= file.raw
        // this.imageUrl = URL.createObjectURL(file.raw);
      },
      beforeAvatarUpload(file) {
        // const isJPG = file.type === 'image/jpeg';
        const isJPG = file.type;
        const isLt2M = file.size / 1024 / 1024 < 2;

        const extension1 = file.type === "image/jpg";
        const extension2 = file.type === "image/jpeg";
        const extension3 = file.type === "image/png";
        if (!extension1 && !extension2 && !extension3) {
          this.$message.error("请上传jpg 、png、jpeg 类型图片!");
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      // 增加行
      // activityType==2:大转盘最多添加6个 activityType==3:九宫格8个
      addRow () {
        console.log("this.tableData",this.tableData)
        if(this.tableData.length > 6 && this.activityType==2){
          this.$message.warning("大转盘最多添加6个奖品")
          return
        }
        if(this.tableData.length > 8 && this.activityType==3){
          this.$message.warning("九宫格最多添加8个奖品")
          return
        }
        var list = {
          prizeName : '',   //奖品名称
          // prizePicture : '',   //奖品图片
          quantity: '',   //数量
          winningPercentage: '',    //中奖率
          medianFrequency: ''   //用户可中次数
        }
        this.tableData.unshift(list)
        console.log('tableData---------add',this.tableData)
      },
      // 删除方法
      // 删除选中行
      deleteRow(index, rows) {
        // 表单删除对应列
        // this.tableData.splice(index, 1)
        rows.splice(index, 1);
        console.log('tableData---------del',this.tableData)
      },
      //  确认提交
      confirm(){
        console.log('确认提交',this.tableData)
        this.$refs.tableData.validate((valid) => {
          console.log("valid============",valid)
          if (valid) {
            if(this.tableData.length > 6 && this.activityType==2){
              this.$message.warning("大转盘最多添加6个奖品")
              return
            }
            if(this.tableData.length > 8 && this.activityType==3){
              this.$message.warning("九宫格最多添加8个奖品")
              return
            }

            if(this.tableData.length>0){
              if(this.tableData.length < 6 && this.activityType==2){
                this.$message.warning("大转盘最低添加6个奖品")
                return
              }
              if(this.tableData.length < 8 && this.activityType==3){
                this.$message.warning("九宫格最低添加8个奖品")
                return
              }
              // this.uploadBj()
              this.$emit('uploadPrice',this.tableData) // 修改
            }
            else{
              this.$message.warning("请添加奖品")
            }
            console.log('可以拿到的数据', this.tableData)
          }
          else{
            //  校检失败
          }
        })
      },
      // 暂未使用
      async uploadBj(){
        // 获取文件上传签名数据
        this.data = await userOssSignature()
        console.log("this.tableData",this.tableData)
        for(let i=0;i<this.tableData.length;i++){
          if(!this.tableData[i].raw){
            break
          }
          console.log("this.tableData[i]",this.tableData[i],this.tableData[i].raw)
          let file = this.tableData[i].raw
          console.log(file)
          let filename=file.name;
          let markIndex=(filename).lastIndexOf('.');
          let suffix=filename.substring(markIndex)
          let date=new Date().getTime();
          // 构建请求参数
          let param = new FormData()
          param.append("key", this.data.dir + date+suffix)
          param.append("policy", this.data.policy)
          param.append("OSSAccessKeyId", this.data.accessId)
          param.append("success_action_status", '200')
          // param.append("callback",  this.data.callback)     //回调（not)
          param.append("signature", this.data.signature)
          param.append("file", file, file.name)
          param.append('success_action_status', '200')
          let config = {
            headers: {
              'Access-Control-Allow-Origin': '*',
              'x-oss-callback-Authorization': getToken()
            }
          }
          console.log("suffix",suffix)
          axios.post(this.data.host, param, config).then(res => {
            if(res.status==200){
              console.log("上传图片成功=======",res)
              console.log('this.data.host',this.data.host+'/'+date+suffix)
              let url=this.data.host+'/'+date+suffix;
              this.tableData[i].prizePicture = url
              // 如需要重复测试，请勿删除raw
              // delete this.tableData[i].raw
              // this.fileList=[]
            }
            else{
              this.$message.error('上传失败');
            }

          }).catch(err => {
            console.log(err)
          })
        }
        setTimeout(()=>{
          console.log("图片上传并删除替换prizePicture地址==========", this.tableData)
          this.$emit('uploadPrice',this.tableData)
        },200)
      },
    }
  }
</script>

<style scoped lang="less">
  /*隐藏input（type=number)右边的小箭头*/
  /deep/.delInput input::-webkit-outer-spin-button,
  /deep/.delInput input::-webkit-inner-spin-button {
    -webkit-appearance: none!important;
  }
  /deep/.delInput input[type="number"]{
    -moz-appearance: textfield;
  }

  .fit-title{
    color: #333333;
    font-size: 16px;
    margin:0px 2px;
  }
  .tj-class{
    margin: 30px 10px 0;
  }
  .avatar-uploader{
    margin: 0;
    padding: 0;
    outline: none;

    /* 修改 start*/
    border: 1px solid #D9D9D9;
    border-radius: 2px;
    /*end*/
    width: 88px;
    height: 88px;
  }
  /*  ‘背景图’上传 start */
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    color: #D9D9D9;
    text-align: center;
    i{
      font-size: 28px;
    }
    div{
      padding-top: 3px;
    }
  }
  .avatar {
    width: 90px;
    height: 90px;
    display: block;
  }
  /*  end*/
</style>
